package fileDemo;

import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author Ajie
 * @date 2023/6/7
 * @function 可能不对 check 的file 都是null
 */
public class BOMDetect_CheckFile {
    //不对、、、
    public static Charset detectBOM(String filePath) {
        BOMInputStream bis = null;
        try {
            bis = new BOMInputStream(new FileInputStream(filePath));
            if (bis.hasBOM(ByteOrderMark.UTF_8)) {
                return Charset.forName("UTF-8");
            } else if (bis.hasBOM(ByteOrderMark.UTF_16BE)) {
                return Charset.forName("UTF-16BE");
            } else if (bis.hasBOM(ByteOrderMark.UTF_16LE)) {
                return Charset.forName("UTF-16LE");
            } else if (bis.hasBOM(ByteOrderMark.UTF_32BE)) {
                return Charset.forName("UTF-32BE");
            } else if (bis.hasBOM(ByteOrderMark.UTF_32LE)) {
                return Charset.forName("UTF-32LE");
            } else {
                return null;
            }
        }catch (Exception e){

            return null;
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                }
            }
        }
//        try (BOMInputStream bis = new BOMInputStream(new FileInputStream(filePath))) {
//            if (bis.hasBOM(ByteOrderMark.UTF_8)) {
//                return Charset.forName("UTF-8");
//            } else if (bis.hasBOM(ByteOrderMark.UTF_16BE)) {
//                return Charset.forName("UTF-16BE");
//            } else if (bis.hasBOM(ByteOrderMark.UTF_16LE)) {
//                return Charset.forName("UTF-16LE");
//            } else if (bis.hasBOM(ByteOrderMark.UTF_32BE)) {
//                return Charset.forName("UTF-32BE");
//            } else if (bis.hasBOM(ByteOrderMark.UTF_32LE)) {
//                return Charset.forName("UTF-32LE");
//            } else {
//                return null;
//            }
//        } catch (IOException e) {
////            e.printStackTrace();
//            return null;
//        }
    }
}
